chrome.webRequest.onHeadersReceived.addListener(
  function (details) {
    var ci_profiling = checkHeaders(details.responseHeaders);
    if (ci_profiling) {
      window.localStorage.clear();
      chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
        var ls = window.localStorage;
        var tabId = ls.getItem('tabId');
        if (tabId == null) {
          alert('调试ing...');
          ls.setItem('tabId', tabs[0].id);
          tabId = tabs[0].id;
        } else {
          tabId = parseInt(tabId);
        }
        chrome.tabs.sendMessage(tabId, ci_profiling, function (response) {
        });
      });
    }
    return {cancel: false};
  },
  {urls: ["*://www.aidaxue.com/*"]},
  ["responseHeaders"]);


var checkHeaders = function(Headers) {
  for (var Header in Headers) {
    if (Headers[Header].name == 'CI-Profiling') {
      return Headers[Header].value;
    }
  }
  return false;
};

var setDomain = function(dm) {
  localStorage.domain = dm
  chrome.webRequest.onHeadersReceived.addListener(
    function (details) {
      var ci_profiling = checkHeaders(details.responseHeaders);
      if (ci_profiling) {
        window.localStorage.clear();
        chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
          var ls = window.localStorage;
          var tabId = ls.getItem('tabId');
          if (tabId == null) {
            alert('调试ing...');
            ls.setItem('tabId', tabs[0].id);
            tabId = tabs[0].id;
          } else {
            tabId = parseInt(tabId);
          }
          chrome.tabs.sendMessage(tabId, ci_profiling, function (response) {
          });
        });
      }
      return {cancel: false};
    },
    {urls: ["*://" + dm + "/*"]},
    ["responseHeaders"]);
};

var getDomain = function() {
  if (localStorage.domain !== null) {
    return localStorage.domain;
  }
  return null;
}